package com.itheima.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <dl>
 * <dd>描述: ~节点业务逻辑实现</dd>
 * <dd>创建时间：  11:02 2020/4/22</dd>
 * <dd>创建人： zz</dd>
 * <dt>版本历史: </dt>
 * <pre>
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2020/4/22      guodong       1.0        1.0 Version
 * </pre>
 * </dl>
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
    * @Date: 11:03 2020/4/22
    * @Param: []
    * @return: List<User>
    * @Description: 查找所有用户
    **/
    @GetMapping("/findAll")
    public List<User> findAll(){
        return userService.findAll();
    }


    /**
    * @Date: 11:23 2020/4/22
    * @Param: []
    * @return: java.lang.String
    * @Description: 增加了缓存的查询所有用户的请求资源
    **/
    @GetMapping("/findAllCache")
    public String findAllCache() throws JsonProcessingException {
        //1.查询redis缓存
        //2.存在返回
        //3.不存在 ----》mysql数据库查找----》转为json字符串存入redis ---》返回


        String usersStr ="";
        usersStr = (String) redisTemplate.boundValueOps("userAll364").get();
        /*if(null != usersStr && "" !=usersStr){

        }*/
        if(StringUtils.isEmpty(usersStr)){ //不存在
            log.info("-----------从mysql数据库中查找-----------------");
            //不存在 ----》mysql数据库查找----》转为json字符串存入redis ---》返回
            List<User> userList = userService.findAll();
            ObjectMapper objectMapper = new ObjectMapper();
            usersStr = objectMapper.writeValueAsString(userList);
            redisTemplate.boundValueOps("userAll364").set(usersStr);
        }
        return usersStr;
    }


}
